import React, {useEffect, useState} from 'react';
import {Avatar, List, message, Pagination, PaginationProps} from "antd";
import {chartShowByPost} from "@/services/ant-design-pro/api";
import {useModel} from "@@/exports";
import ReactECharts from "echarts-for-react";

// 搜索参数
const searchParams = {
  uploadUserId: undefined,
  pageNum: 0,
  pageSize: 5
};

const ChartShow: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [current, setCurrent] = useState(0);
  const [chartShowResult, setChartShowResult] = useState({
    data: [],
    total: 0
  });

  // 加载页面数据
  const loadData = async () => {
    const res = await chartShowByPost({
      ...searchParams,
      uploadUserId: initialState.currentUser.id
    });
    if (res.code !== 200) {
      message.error('获取图表数据失败!');
      return;
    }
    message.success('获取图表数据成功!');
    setChartShowResult(res.data);
  }

  const onChange: PaginationProps['onChange'] = (page) => {
    setCurrent(page);
    searchParams.pageNum = page;
    loadData() // 重新调用loadData获取数据
  };

  useEffect(() => {
    loadData(); // 加载数据
  }, [searchParams]);

  return (
    <div>
        <List
        itemLayout="vertical"
        size="large"
        dataSource={chartShowResult.data}
        renderItem={(item) => (
          <div>
          <List.Item
            key={item.id}
          >
            <List.Item.Meta
              avatar={<Avatar src={item.avatar}/>}
              title={<a href={item.href}>{item.chartName}</a>}
              description={item.goal}
            />
            {item.genResult}
          </List.Item>
          <ReactECharts option={JSON.parse(item.genData ? item.genData : '{}')}></ReactECharts>
          </div>
        )}
      />
      <Pagination onChange={onChange} current={current} pageSize={searchParams.pageSize} defaultCurrent={1}  total={chartShowResult.total} />
    </div>
  )
};

export default ChartShow;
